package com.suixinsanren.design.command.demo02;

public class RemoteControl {

    private Command[] onCommands;
    private Command[] offCommands;
    private Command undoCommand;

    public RemoteControl(int slot) {
        onCommands = new Command[slot];
        offCommands = new Command[slot];
        undoCommand = new NoCommand();
    }

    public void setCommand(int slot, Command onCommand, Command offCommand) {
        checkSlot(slot, onCommands);
        checkSlot(slot, offCommands);
        onCommands[slot] = onCommand;
        offCommands[slot] = offCommand;
    }

    public void onButtonWasPushed(int slot) {
        checkSlot(slot, onCommands);
        onCommands[slot].execute();
        undoCommand = onCommands[slot];
    }

    public void offButtonWasPushed(int slot) {
        checkSlot(slot, onCommands);
        offCommands[slot].execute();
        undoCommand = offCommands[slot];
    }

    public void undo() {
        undoCommand.undo();
    }

    private void checkSlot(int slot, Command[] commands) {
        if (commands == null) {
            throw new IllegalArgumentException("未初始化");
        }
        if (slot < 0 || slot >= commands.length) {
            throw new IllegalArgumentException("槽位不存在");
        }
    }
}
